package cn.Alibaba.user.service.impl;

import cn.Alibaba.basic.constant.VerifyConstants;
import cn.Alibaba.basic.exception.BusinessException;
import cn.Alibaba.basic.jwt.JwtUtils;
import cn.Alibaba.basic.jwt.LoginData;
import cn.Alibaba.basic.jwt.RsaUtils;
import cn.Alibaba.basic.util.HttpUtil;
import cn.Alibaba.basic.util.JsonResult;
import cn.Alibaba.basic.util.Md5Utils;
import cn.Alibaba.basic.util.StrUtils;
import cn.Alibaba.system.domain.Menu;
import cn.Alibaba.user.constant.WxConstants;
import cn.Alibaba.user.domain.Logininfo;
import cn.Alibaba.user.domain.User;
import cn.Alibaba.user.domain.Wxuser;
import cn.Alibaba.user.dto.BinderDto;
import cn.Alibaba.user.dto.LoginDto;
import cn.Alibaba.user.mapper.LogininfoMapper;
import cn.Alibaba.user.mapper.UserMapper;
import cn.Alibaba.user.mapper.WxuserMapper;
import cn.Alibaba.user.service.ILogininfoService;
import cn.Alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.sql.Struct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;



    // 账号登录
    @Override
    public Map<String, Object> getLoginin(LoginDto dto) {

        String account = dto.getAccount();
        String password = dto.getPassword();
        Integer loginType = dto.getLoginType();

        // 校验参数
        if (StringUtils.isEmpty(account)||StringUtils.isEmpty(password)||
                StringUtils.isEmpty(loginType)){

            throw new BusinessException("参数不能为空");

        }

        // 校验账号
        Logininfo logininfo =  logininfoMapper.loadByAccount(dto);

        if (logininfo==null){
            throw new BusinessException("用户名不存在");
        }

        // 校验密码是否正确
        // 加盐加密后的密码
        String md5Pwd = Md5Utils.encrypByMd5(password + logininfo.getSalt());
        if (!md5Pwd.equals(logininfo.getPassword())){

            throw new BusinessException("密码错误，请重新输入");

        }

//        String token = UUID.randomUUID().toString();
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//
//
//        HashMap<String, Object> map = new HashMap<>();
//
//        map.put("token",token);
//        map.put("logininfo",logininfo);

        Map<String ,Object> map = loginSuccessJwtHandler(logininfo);


        return map;
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {

        LoginData loginData = new LoginData();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        loginData.setLogininfo(logininfo);
        HashMap<String, Object> map = new HashMap<>();

        try {

            if (logininfo.getType()==0){
                // 获取所有权限
             Long id =logininfo.getId();
                System.out.println(id);

                List<String> permissions = logininfoMapper.loadPermissionsByLogininfoId(logininfo.getId());

                permissions.forEach(System.out::println);
                // 获取登录人的对应的所有菜单
                List<Menu> menus = logininfoMapper.loadMenusBylogininfoId(logininfo.getId());
                loginData.setMenus(menus);
                loginData.setPermissions(permissions);

                map.put("menus",menus);
                map.put("permissions",permissions);

            }

            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());

            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30000000);

            map.put("token",jwtToken);
            map.put("logininfo",logininfo);

            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;


    }

    //微信登录
    @Override
    public JsonResult wechatLoginin(String code) {

        // 1.根据code发送请求获取token和openid
        String url = WxConstants.GET_ACK_URL
                .replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);

        String jsonUrl = HttpUtil.httpGet(url);
       //{"access_token":"59_RcCbvEVd5d5y5Eh7-AcrgcpnwnqLWLTaKv4kDL-Cpk8WqxI797lg1MBFUUqO-QDb01siGa_Wc0GT5eq8B_uq1kTyct1QJ-eQJVDdubWNmq4","openid":"oa9wA02zP9QKbjVrdAEI1wza41Sw",


        // 2.将响应的json字符串 转成json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonUrl);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        // 3. 通过openid去t_wxuser中查询
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);

        // 4. 如果有 就说明绑定过 直接免密登录
        if (wxuser!=null && wxuser.getUserId()!=null){// 说明绑定了

            // 查到logininfo对象
            Logininfo logininfo = logininfoMapper.loadLogininfoByUserId(wxuser.getUserId());

//            String token = UUID.randomUUID().toString();
//            logininfo.setPassword(null);
//            logininfo.setSalt(null);
//
//            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//
//
//            HashMap<String, Object> map = new HashMap<>();
//
//            map.put("token",token);
//            map.put("logininfo",logininfo);

            Map<String ,Object> map = loginSuccessJwtHandler(logininfo);

            return JsonResult.me().setResultObj(map);


        }else {

            // 5.如果没有，就说明没有绑定过 就需要跳转页面 ，响应给前端跳转页面
            HashMap<String, Object> map = new HashMap<>();

            map.put("access_token",access_token);
            map.put("openid",openid);

           return JsonResult.me().setSuccess(false).setResultObj(map);


        }
    }


    // 微信绑定
    @Override
    public JsonResult wechatBinder(BinderDto binderDto) {

        // 校验空值
        String phone = binderDto.getPhone();
        String verifyCode = binderDto.getVerifyCode();
        String openId = binderDto.getOpenId();
        String accessToken = binderDto.getAccessToken();

        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(verifyCode)){

            throw  new BusinessException("数据不能为空");
        }

        // 校验验证码是否过期VerifyConstants
        Object redisCode = redisTemplate.opsForValue().get(phone +VerifyConstants.BINDER_PREFIX );
        System.out.println(redisCode);
        if (redisCode==null){
            throw  new BusinessException("验证码已过期！请重新输入");
        }
        // 校验验证码是否正确
        if (!redisCode.toString().split(":")[0].equalsIgnoreCase(verifyCode)){
            throw  new BusinessException("验证码错误");
        }

        String url = WxConstants.GET_USER_URL
                .replace("ACCESS_TOKEN",accessToken)
                .replace("OPENID",openId);

        String jsonStr = HttpUtil.httpGet(url);
        Wxuser wxuser =  jsonStr2Wxuser(jsonStr);// user_id


        // 通过phone查询user
        User user = userMapper.loadByPhone(phone);

        if (user==null){
            user = phone2User(phone);
            Logininfo logininfoTom = user2Logininfo(user);

            logininfoMapper.add(logininfoTom);
            user.setLogininfoId(logininfoTom.getId());
            userMapper.add(user);
        }

        wxuser.setUserId(user.getId());

        wxuserMapper.add(wxuser);

        // 做免密登录
        Logininfo logininfo = logininfoMapper.loadOne(user.getLogininfoId());
        System.out.println(logininfo);
//        String token = UUID.randomUUID().toString();
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//
//
//        HashMap<String, Object> map = new HashMap<>();
//
//        map.put("token",token);
//        map.put("logininfo",logininfo);

        Map<String ,Object> map = loginSuccessJwtHandler(logininfo);

        return JsonResult.me().setResultObj(map);
    }



    private Wxuser jsonStr2Wxuser(String jsonStr) {

        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);

        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country")+jsonObject.getString("province")+jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String randomPwd = StrUtils.getRandomString(6);
        String md5Pwd = Md5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    @Override
    public void logout(String token) {

        redisTemplate.delete("token");

    }





}
